//
//  AddACarnivalViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/15/12.
//  Copyright 2012 Muludiang. All rights reserved.
//

#import "AddACarnivalViewController.h"
#import "StackMob.h"
#import "iBacchanal.h"

@implementation AddACarnivalViewController

@synthesize country;
@synthesize startDate;
@synthesize endDate;
@synthesize datePicker;
@synthesize countryPicker;
@synthesize countries;
@synthesize hideKeyboardButton;
@synthesize carnivalTitle;
@synthesize city, state;
@synthesize phoneNumber, website;
@synthesize scrollView;

-(IBAction)cancelSubmit:(UIBarButtonItem *)sender{
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)hideKeyboard:(UIButton *)sender{
	[country resignFirstResponder];
	[startDate resignFirstResponder];
	[endDate resignFirstResponder];
	[carnivalTitle resignFirstResponder];
	[city resignFirstResponder];
	[state resignFirstResponder];
}


-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)countryNamePicker{
	return 1;
}


-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
	return [self.countries count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	return [countries objectAtIndex:row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
	[country setText: [countries objectAtIndex:row]];
}


-(IBAction)pickDate:(id)sender{
	
	NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
	[dateFormat setDateFormat:@"yyyy-MM-dd"];	

	if ([startDate isFirstResponder]) {
		[startDate setText:[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:datePicker.date]]];
	}
	else {
		[endDate setText:[NSString stringWithFormat:@"%@",[dateFormat stringFromDate:datePicker.date]]];
	}
	
	[dateFormat release];
	
}

-(IBAction)submitCarnival:(UIBarButtonItem *)sender{
	
	if ([[city text]length] == 0 || [[country text] length] == 0 || [[startDate text] length] == 0 || [[endDate text] length] == 0){
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Please make sure all required fields are filled out"  delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
		else{
			iBacchanal *bacchanal = [iBacchanal sharedUser];
	NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
						  carnivalTitle.text, @"carnivalTitle", city.text, @"city", state.text, @"state",
						  startDate.text, @"startDate", endDate.text, @"endDate", country.text, @"country",
						  @"0", @"hidden", bacchanal.currentUser, @"submittedBy", phoneNumber.text, @"phoneNumber", website.text, @"website", nil];
	[[StackMob stackmob] post:@"carnivals" withArguments:args andCallback:^(BOOL success, id result) {
		if (success) {
			bacchanal.dataChanged = YES;
			UIAlertView *submitAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Carnival information successfully submitted." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			submitAlert.tag = 1;
			[submitAlert show];
			//[submitAlert release];
			
			//NSDictionary *resultObj = (NSDictionary *)result;
			//NSString *itemId = [resultObj objectForKey:@"chatmessage_id"];
			// …
		} else {
			// handle object creation failure
			NSLog(@"Something's wrong....%@", result);
		}
	}];
		}
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (alertView.tag == 1){
	iBacchanal *bacchanal = [iBacchanal sharedUser];

	[[StackMob stackmob] get:@"carnivals" withCallback:^(BOOL success, id result) {
		if (success) {
			bacchanal.carnivalsData = [[NSArray alloc] initWithArray:result];
			// object found, cast result to NSArray* and continue with processing
		} else {
			// unable to retrieve object, cast result to NSError* and inspect code & message
			NSLog(@"Error:");
		}
	}];
	[alertView release];
		[self dismissModalViewControllerAnimated:YES];
	}
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelSubmit:)] autorelease];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(submitCarnival:)] autorelease];
	self.navigationItem.title = @"Submit Carnival";
	
	scrollView.frame = CGRectMake(0, 0, 320, 416);
	[scrollView setContentSize:CGSizeMake(320, 350)];
	
	[startDate setInputView:datePicker];
	[endDate setInputView:datePicker];
	[country setInputView:countryPicker];
	
	countries = [[NSMutableArray alloc] init]; 
	NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier: @"en_US"] autorelease];
	
	NSArray *countryArray = [NSLocale ISOCountryCodes]; 
	for (NSString *countryCode in countryArray) 
	{
		NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
		
		NSString *displayNameString = [locale displayNameForKey:NSLocaleCountryCode value:countryCode];
		[countries addObject:displayNameString];
		[pool release];
		
	}
	
	[countries sortUsingSelector:@selector(compare:)];
	
}

-(void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:YES];
	//---registers the notifications for keyboard---
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidShow:)
												 name:UIKeyboardDidShowNotification
											   object:self.view.window];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardDidHide:)
												 name:UIKeyboardDidHideNotification
                                               object:nil];
}

//---when a TextField view begins editing---
-(void) textFieldDidBeginEditing:(UITextField *)textFieldView {  
	currentTextField = textFieldView;
} 

/*
 -(void)textViewDidBeginEditing:(UITextView *)textView{
	currentTextView = textView;
}
*/

-(BOOL) textFieldShouldReturn:(UITextField *) textFieldView {  
	[textFieldView resignFirstResponder];
	return YES;
}

//---when a TextField view is done editing---
-(void) textFieldDidEndEditing:(UITextField *) textFieldView {  
	currentTextField = nil;
}

/*
-(void)textViewDidEndEditing:(UITextView *)textView{
	currentTextView = nil;
}
*/


//---when the keyboard appears---
-(void) keyboardDidShow:(NSNotification *) notification {
	if (keyboardIsShown) return;
	
	NSDictionary* info = [notification userInfo];
	
	//---obtain the size of the keyboard---
	NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
    
	//---resize the scroll view (with keyboard)---
	CGRect viewFrame = [scrollView frame];
	viewFrame.size.height -= keyboardSize.height;
	scrollView.frame = viewFrame;
	
	//---scroll to the current text field---
	if (currentTextField != nil){
		
		CGRect textFieldRect = [currentTextField frame];
		[scrollView scrollRectToVisible:textFieldRect animated:YES];
	}
	
	/*if (currentTextView != nil){
		CGRect textViewRect = [currentTextView frame];
		[scrollView scrollRectToVisible:textViewRect animated:YES];
	}*/
	
	keyboardIsShown = YES;
}


//---when the keyboard disappears---
-(void) keyboardDidHide:(NSNotification *) notification {
	NSDictionary* info = [notification userInfo];
	
	//---obtain the size of the keyboard---
	NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
	CGSize keyboardSize = [aValue CGRectValue].size;
	
	//---resize the scroll view back to the original size (without keyboard)---
	CGRect viewFrame = [scrollView frame];
	viewFrame.size.height += keyboardSize.height;
	scrollView.frame = viewFrame;
	
	keyboardIsShown = NO;
}

-(void) viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:YES];
	//---removes the notifications for keyboard---
	[[NSNotificationCenter defaultCenter]
	 removeObserver:self
	 name:UIKeyboardWillShowNotification
	 object:nil];
	[[NSNotificationCenter defaultCenter]
	 removeObserver:self
	 name:UIKeyboardWillHideNotification
	 object:nil];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[scrollView release];
	[website release];
	[phoneNumber release];
	[state release];
	[city release];
	[hideKeyboardButton release];
	[datePicker release];
	[countryPicker release];
	[startDate release];
	[endDate release];
	[country release];
    [super dealloc];
}


@end
